package dom.servlet;

import java.io.IOException;
import java.util.Date;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dom.util.CookieUtil;
import dom.bean.User;
import dom.dao.UserDao;
import domi.service.UserService;

public class Login extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public Login() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		String stuCode=request.getParameter("logstuCode");
		String password=request.getParameter("logpsw");
		String remeber=request.getParameter("remember");

		User user=null;
		user = UserDao.findByCodeAndPass(stuCode, password);

		if(user==null){
			request.setAttribute("logError", "账号或密码，请重新输入");
			request.getRequestDispatcher("../Login.jsp").forward(request,response);
		}else{
				request.getSession().setAttribute("session_user", user);
				request.getSession().setAttribute("id", user.stuCode);
				request.getSession().setAttribute("time",new Date());
				if(remeber!=null && remeber.equals("remember-me")){
					CookieUtil.addCookie("cookie_name_pass",7*24*60*60,request,response,stuCode,password);
				}
				request.getRequestDispatcher("../Main.jsp").forward(request,response);
			}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
}
